package com.storeapp.ui;

import java.sql.Date;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.INullSelectionListener;
import org.eclipse.ui.IViewReference;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.layout.GridData;

import com.storeapp.entity.domain.Product;
import com.storeapp.service.ProductService;
import com.storeapp.util.SpringUtils;

public class ProductEditView extends ViewPart implements INullSelectionListener {
	public static final String ID = "com.storeapp.ui.ProductEditView";

	private Text nameText;
	private Text priceText;
	private Text providerText;
	private Text dscrpText;
	private Text arrTimeText;
	private Text guarenteeText;

	private Label nameInvalidLabel;
	private Label priceInvalidLabel;
	private Label pvdrInvalidLabel;
	private Label dscrpInvalidLabel;
	private Label arrTimeInvalidLabel;
	private Label guteInvalidLabel;

	private ArrayList<IPropertyChangeListener> listeners;
	public static String actionType;
	private Product product;
	private Product oldProduct;

	private ProductService productService;

	public ProductEditView() {
		product = new Product();
		oldProduct = new Product();
		this.productService = (ProductService) SpringUtils
				.getApplicationContext().getBean("productService");
		this.listeners = new ArrayList<IPropertyChangeListener>();
	}

	@Override
	public void createPartControl(Composite parent) {
		// TODO Auto-generated method stub
		parent.setLayout(new GridLayout(5, true));
		// productName
		Label nameLabel = new Label(parent, SWT.NONE);
		nameLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		nameLabel.setText("名称：");
		nameText = new Text(parent, SWT.BORDER);
		nameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
				3, 1));
		nameInvalidLabel = new Label(parent, SWT.NONE);

		// price
		Label priceLabel = new Label(parent, SWT.NONE);
		priceLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		priceLabel.setText("价格：");
		priceText = new Text(parent, SWT.BORDER);
		priceText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
				3, 1));
		priceInvalidLabel = new Label(parent, SWT.NONE);

		// provider
		Label providerLabel = new Label(parent, SWT.NONE);
		providerLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		providerLabel.setText("进货商：");
		providerText = new Text(parent, SWT.BORDER);
		providerText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false, 3, 1));
		pvdrInvalidLabel = new Label(parent, SWT.NONE);

		// description
		Label dscrpLabel = new Label(parent, SWT.NONE);
		dscrpLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		dscrpLabel.setText("描述：");
		dscrpText = new Text(parent, SWT.BORDER);
		dscrpText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
				3, 1));
		dscrpInvalidLabel = new Label(parent, SWT.NONE);

		// arrivalTime
		Label arrTimeLabel = new Label(parent, SWT.NONE);
		arrTimeLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		arrTimeLabel.setText("进货时间：");
		arrTimeText = new Text(parent, SWT.BORDER);
		arrTimeText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false, 3, 1));
		arrTimeInvalidLabel = new Label(parent, SWT.NONE);

		// guarentee
		Label guarenteeLabel = new Label(parent, SWT.NONE);
		guarenteeLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		guarenteeLabel.setText("保修：");
		guarenteeText = new Text(parent, SWT.BORDER);
		guarenteeText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false, 3, 1));
		guteInvalidLabel = new Label(parent, SWT.NONE);

		// button
		Label placeHolderLeft = new Label(parent, SWT.NONE);
		placeHolderLeft.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false, 1, 1));
		Button saveButton = new Button(parent, SWT.NONE);
		saveButton.setText("确定");
		saveButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {

				if (actionType.equals("update")) {
					oldProduct = product;
				}
				product.setProductName(nameText.getText());
				product.setDescription(dscrpText.getText());
				product.setGuarentee(guarenteeText.getText());
				product.setProvider(providerText.getText());
				product.setArrivalTime(Date.valueOf(arrTimeText.getText()));
				Pattern p = Pattern.compile("[^0-9.]");
				Matcher m = p.matcher(priceText.getText());
				product.setPrice(Double.valueOf(m.replaceAll("")));
				productService.saveOrUpdateProduct(product);

				notifyListeners();
			}
		});

		Button cancelButton = new Button(parent, SWT.NONE);
		cancelButton.setText("取消");
		cancelButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				IViewReference view = getSite().getPage().findViewReference(ProductEditView.ID);
				getSite().getPage().hideView(view);
			}
		});
		Label placeHolderRight = new Label(parent, SWT.NONE);

		if (actionType.equals("update")) {
			getSite().getPage().addSelectionListener(ProductList.ID, this);
			fillText();
		}

		// add property listener to notify orderlist view to update list
		addPropertyChangeListener((IPropertyChangeListener) getSite()
				.getWorkbenchWindow().getActivePage().findView(ProductList.ID));
	}

	// A public method that allows listener registration
	public void addPropertyChangeListener(IPropertyChangeListener listener) {
		if (!listeners.contains(listener))
			listeners.add(listener);
	}

	// A public method that allows listener registratINullSelectionListenerion
	public void removePropertyChangeListener(IPropertyChangeListener listener) {
		listeners.remove(listener);
	}

	public void notifyListeners() {
		// Post Invocation, inform listeners
		for (Iterator<IPropertyChangeListener> iter = listeners.iterator(); iter
				.hasNext();) {
			IPropertyChangeListener element = iter.next();
			if (actionType.equals("update")) {
				element.propertyChange(new PropertyChangeEvent(this,
						"updateProduct", oldProduct, product));
			} else {
				element.propertyChange(new PropertyChangeEvent(this,
										"AddNewProduct", null, null));
			}

		}
	}

	private void fillText() {
		StructuredSelection sel = (StructuredSelection) getSite().getPage()
				.getSelection(ProductList.ID);
		product = (Product) sel.getFirstElement();
		nameText.setText(product.getProductName());
		priceText.setText(String.format("￥ %(,.2f", product.getPrice()));
		providerText.setText(product.getProvider());
		dscrpText.setText(product.getDescription());
		arrTimeText.setText(String.format("%1$tY-%1$tm-%1$te",
				product.getArrivalTime()));
		guarenteeText.setText(product.getGuarentee());
	}

	@Override
	public void setFocus() {
		// TODO Auto-generated method stub
	}

	@Override
	public void selectionChanged(IWorkbenchPart part, ISelection selection) {
		// TODO Auto-generated method stub
		if (selection instanceof StructuredSelection
				&& ((StructuredSelection) selection).getFirstElement() instanceof Product) {
			product = (Product) ((StructuredSelection) selection)
					.getFirstElement();
			nameText.setText(product.getProductName());
			priceText.setText(String.format("￥ %(,.2f", product.getPrice()));
			providerText.setText(product.getProvider());
			dscrpText.setText(product.getDescription());
			arrTimeText.setText(String.format("%1$tY-%1$tm-%1$te",
					product.getArrivalTime()));
			guarenteeText.setText(product.getGuarentee());
		}
	}

	@Override
	public void dispose() {
		super.dispose();
		getSite().getPage().removeSelectionListener(ProductList.ID, this);
	}
}
